﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;

using Topshelf;
using Topshelf.Logging;

using YTS.Logic.Log;

using Newtonsoft.Json;
using Microsoft.Extensions.Configuration;

namespace RunQuartzConsole
{
    public class CommandScriptService : ServiceControl, ILog
    {
        private Timer _timer;
        private readonly LogWriter _logger;
        private readonly string[] timerRegexs;
        private readonly string ExePath;
        private readonly string WindowLoginUserName;

        public CommandScriptService()
        {
            _logger = HostLogger.Get<CommandScriptService>();
            _logger.Info("Init new CommandScriptService()");

            var _configuration = new ConfigurationBuilder()
                .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                .AddJsonFile("appsettings.json")
                .Build();
            timerRegexs = _configuration.GetSection("TimerRegexs").Get<string[]>();
            ExePath = _configuration.GetSection("ExePath").Get<string>();
            WindowLoginUserName = _configuration.GetSection("WindowLoginUserName").Get<string>();
            _logger.Info($"GetArgs.TimerRegexs: {JsonConvert.SerializeObject(timerRegexs)}");
            _logger.Info($"GetArgs.ExePath: {ExePath}");
            _logger.Info($"GetArgs.WindowLoginUserName: {WindowLoginUserName}");
        }

        public bool Start(HostControl hostControl)
        {
            _logger.Info("CommandScriptService.Start()");

            var dueTime = Calc_Timer_dueTime();
            _logger.Info($"延时总毫秒数: {dueTime.TotalMilliseconds}");
            _timer = new Timer(b => TimerCallbackFunction(), null, dueTime, Timeout.InfiniteTimeSpan);

            _logger.Info("timer = new Timer(): 1分钟执行一次");
            return true;
        }
        public bool Stop(HostControl hostControl)
        {
            _logger.Info("CommandScriptService.Stop()");
            _timer.Dispose();
            _logger.Info("timer.Dispose()");
            return true;
        }
        private static TimeSpan Calc_Timer_dueTime()
        {
            DateTime nt = DateTime.Now;
            var tt = new DateTime(nt.Year, nt.Month, nt.Day, nt.Hour, nt.Minute, 0, 0, nt.Kind).AddMinutes(1);
            var span = tt - nt;
            return span;
        }

        public void TimerCallbackFunction()
        {
            _logger.Info("CommandScriptService.TimerCallbackFunction run...");
            try
            {
                DateTime nowTime = DateTime.Now;
                string nowTimeString = nowTime.ToString("HH:mm");
                if (timerRegexs.Contains(nowTimeString))
                {
                    _logger.Info($"当前时间为: {nowTimeString}, 执行触发脚本命令...");
                    var help = new CommandExecutionHelp(this);
                    help.OpenDingDingHintAPP_ApplicationLoader(ExePath, WindowLoginUserName);
                }
                var dueTime = Calc_Timer_dueTime();
                _logger.Info($"延时总毫秒数: {dueTime.TotalMilliseconds}");
                _timer.Change(dueTime, Timeout.InfiniteTimeSpan);
            }
            catch (Exception ex)
            {
                _logger.Error("CommandScriptService.TimerCallbackFunction run Show Error!!!", ex);
            }
        }

        public void Info(string message, params IDictionary<string, object>[] args)
        {
            string json = JsonConvert.SerializeObject(args);
            _logger.Info($"消息:{message}, 附带参数: {json}");
        }

        public void Error(string message, params IDictionary<string, object>[] args)
        {
            string json = JsonConvert.SerializeObject(args);
            _logger.Error($"消息:{message}, 附带参数: {json}");
        }

        public void Error(string message, Exception ex, params IDictionary<string, object>[] args)
        {
            string json = JsonConvert.SerializeObject(args);
            _logger.Error($"消息:{message}, 附带参数: {json}", ex);
        }
    }
}
